package com.wzf.greattruth.zookeeper.operator;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

public class ZooKeeperCreateParentDirOperator extends ZooKeeperOperator<Void, Boolean> {

    public ZooKeeperCreateParentDirOperator(ZooKeeper zookeeper, String path, byte[] datas, CreateMode mode) {
        super(zookeeper, path, datas, mode);
    }

    public Boolean operate() throws KeeperException, InterruptedException {
        return super.operate(null);
    }

    @Override
    public synchronized Boolean doOperate(Void param) throws KeeperException, InterruptedException {
        ZooKeeper zookeeper = getZookeeper();
        String parentDir = getDir();
        byte[] datas = getDatas();
        CreateMode mode = getMode();
        List<ACL> acl = getAcl();

        Stat stat = zookeeper.exists(parentDir, false);
        if (stat != null) {
            return true;
        }

        String[] dirs = parentDir.split(File.separator);
        StringBuffer sb = new StringBuffer(File.separator);
        for (String dir : dirs) {
            if (StringUtils.isBlank(dir)) {
                continue;
            }
            sb.append(dir);
            String zkDir = sb.toString();
            Stat stat1 = zookeeper.exists(zkDir, false);
            if (stat1 == null) {
                zookeeper.create(zkDir, datas, acl, mode);
            }
            sb.append(File.separator);
        }
        return true;
    }

}
